import * as vant from 'vant'
import * as bsc from '@/contract/bsc'
import * as home from '@/api/home'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const user = computed(() => userStore.user)

let signer: any = null

export const check = async () => {
  if (!window.ethereum) {
    vant.showFailToast({ message: '请安装MetaMask或其他Ethereum钱包扩展。', duration: 3000 })
    return false
  }
  if (!user.value.address) {
    connect()
  }
  const ret = await bsc.checkWallet(user.value.address)
  if (!ret) {
    connect()
  }
}

export const connect = async () => {
  if (!window.ethereum) {
    vant.showFailToast({ message: '请安装MetaMask或其他Ethereum钱包扩展。', duration: 3000 })
    return false
  }
  signer = await bsc.connectWallet()
  const address = await signer.getAddress()
  console.log('signer address:', address)
  if (!address) {
    user.value.address = ''
    return
  }
  await login(address)
}

export const login = async (address: string) => {
  await home
    .login(address)
    .then(async ret => {
      console.log('login success:', ret.data)
      window.sessionStorage.setItem('token', ret.data.address)
      userStore.setUser(ret.data)
      user.value.address = address
      user.value.balance = await getBalance()
      if (user.value.state == 1) {
        user.value.link = `https://www.aigxt.app?ref=${address}`
      } else {
        user.value.link = '请先购买激活'
      }
    })
    .catch(ret => {
      console.log('login error:', ret)
      vant.showFailToast({ message: ret.message, duration: 3000 })
    })
}

// 调用导出的函数
export async function getBalance() {
  return await bsc.getWalletBalance(signer)
}

// 购买
export async function buy() {
  if (!signer) {
    vant.showFailToast({ message: '请先连接钱包', duration: 3000 })
    return
  }
  if (user.value.ref == '') {
    vant.showFailToast({ message: '参数错误', duration: 3000 })
    return
  }
  console.log('开始调用 transferBNB...')
  const ret = await bsc.callTransferBNB(user.value.ref, '0.2')
  console.log('callTransferBNB ret:', ret)
  if (ret) {
    await home.active(user.value.address)
    await login(user.value.address)
  }
  console.log('transferBNB 调用完成')
}

export async function getAddress() {
  return await signer.address
}
